package com.mantru.iotpot.dishes

import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.databinding.Observable
import androidx.databinding.ObservableField
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Bean.DishesChooseBean
import com.mantru.iotpot.Util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject

class DishesCreateChooseViewModel(application: Application) : AndroidViewModel(application) {

    //食材搜索文本框内容
    val foodSearch = ObservableField<String>("")
    //前面页面带进来的已选择材料
    var existName = ""
    // 数据集合
    val nameList = ObservableField<MutableList<String>>()
    private val _dishesChooseList = MutableLiveData<MutableList<DishesChooseBean>>()
    val dishesChooseList: LiveData<MutableList<DishesChooseBean>> = _dishesChooseList
    //存储返回的数据列表
    val selectedFoodList = MutableLiveData<MutableList<String>>()
    private val applicationClass: ApplicationClass = application as ApplicationClass


    // 初始化viewModel
    init {
        nameList.set(mutableListOf())
        selectedFoodList.value = mutableListOf()
    }

    //监听输入框的内容，当为空时重新获取数据
    fun startListeningToFoodSearch() {
        foodSearch.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                val searchQuery = foodSearch.get().toString()
                if (searchQuery.isEmpty()) {
                    // 当搜索框为空时，重新获取数据
                    val map: MutableMap<String, Any> = HashMap()
                    map["count"] = 100
                    getHttpValue("GetSQLData_Vegetable_List_Base", map)
                }
            }
        })
    }

    //筛选出输入框文字的内容，并重新赋值_dishesChooseList
    fun performSearch() {
        val searchQuery = foodSearch.get().toString()
        if (searchQuery.isNotEmpty()) {
            // 筛选数据并映射为字符串列表
            val filteredNames = dishesChooseList.value?.filter {
                it.name.contains(searchQuery, ignoreCase = true)
            }?.map { it.name }?.toMutableList() ?: mutableListOf()
            // 更新 nameList
            nameList.set(filteredNames)
            // 更新 dishesChooseList
            updateDishesList()
        }
    }

    // 更新菜谱研发列表数据
    private fun updateDishesList() {
        //确保在主线程进行
        viewModelScope.launch(Dispatchers.Main) {
            val newList = mutableListOf<DishesChooseBean>()
            if (nameList.get()?.isNotEmpty() == true) {
                for (i in 0 until nameList.get()!!.size) {
                    val name = nameList.get()?.get(i).toString()
                    val isSelected = selectedFoodList.value?.contains(name) ?: false
                    newList.add(DishesChooseBean(
                        name = name,
                        isSelected = isSelected))
                }
            }
            _dishesChooseList.postValue(newList)
        }
    }

    //获取网络数据
    fun getHttpValue(api: String, map: Map<String, Any>){
        when ( api ){
            "GetSQLData_Vegetable_List_Base" ->{//读取基础食材列表
                val jsonData = applicationClass.GetSQLData_Vegetable_List_Base(map["count"] as Int)
                // 处理jsonData为空的情况
                if (!jsonData.isNullOrEmpty()) {
                    try {
                        val jsonObject = JSONObject(jsonData)
                        val success = jsonObject.getBoolean("success")
                        if (success) {
                            nameList.get()?.clear()
                            val itemDataArray = jsonObject.getJSONArray("item_data")
                            if ( itemDataArray.length() > 0 ){
                                for (i in 0 until itemDataArray.length()) {
                                    val jsonItem = itemDataArray.getJSONObject(i)
                                    nameList.get()?.add(jsonItem.getString("base_name"))
                                    if (existName.isNotEmpty() ) {
                                        selectedFoodList.value?.add(existName)
                                        existName = ""//只有第一次处理该事件
                                    }
                                }
                            }
                            updateDishesList()
                        } else {
                            Log.e("---GetSQLData_Vegetable_List_Base", "API返回success=false")
                        }
                    } catch (e: Exception){
                        Log.e("---GetSQLData_Vegetable_List_Base:",e.toString())
                    }
                } else {
                    Log.e("---GetSQLData_Vegetable_List_Base", "返回的JSON数据为空")
                }
            }
            "SaveSQLData_Vegetable_Base" ->{
                val jsonData = applicationClass.SaveSQLData_Vegetable_Base(map["base_name"] as String)
                if ( jsonData ){
                    //Toast.makeText(applicationClass, "保存成功", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(applicationClass, "保存成功")
                    foodSearch.set("")
                } else {
                    //Toast.makeText(applicationClass, "保存失败", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(applicationClass, "保存失败")
                }
            }
        }
    }
}